package com.maxd.modules.selfshop.merchants.service;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.modules.selfshop.merchants.entity.SelfStore;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreCollectJpaRepository;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreJpaRepository;
import com.maxd.respository.admin.AdminJpaRepository;
import com.maxd.respository.selfGoods.GoodsJpaRepository;
import com.maxd.respository.selfUser.SelfUserBrowseJpaRepository;
import com.maxd.service.selfOrder.OrdersService;
import com.maxd.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SelfStoreServiceImpl implements SelfStoreService{
    @Autowired
    private SelfStoreJpaRepository jpaRepository;
    @Autowired
    private AdminJpaRepository adminJpaRepository;

    @Override
    public Result findAll(Integer page, Integer size, String storeName) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //构造自定义查询条件
        Specification<SelfStore> queryCondition = new Specification<SelfStore>() {
            @Override
            public Predicate toPredicate(Root<SelfStore> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(storeName)) {
                    predicateList.add(criteriaBuilder.like(root.get("storeName"), "%"+storeName+"%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        Page<SelfStore> all = jpaRepository.findAll(queryCondition, pageable);
        List<SelfStore> content = all.getContent();
        for(SelfStore selfStore:content){
            selfStore.setAdminInfo(adminJpaRepository.findAdminInfoByStoreId(selfStore.getStoreId()));
        }
        return ResultUtil.success(all);
    }

    @Override
    public Result saveBody(SelfStore entity) {
        entity.setCreateTime(DateUtil.createTime());
        entity.setSale(0); //销量为0
        entity.setBanStatus(1);
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result updateBody(SelfStore entity) {
        //判断店铺名称
        SelfStore s = jpaRepository.checkStoreName(entity.getStoreName());
        if (s != null && entity.getStoreId() != s.getStoreId()){
            return ResultUtil.error(-1,"店铺名称重复");
        }
        entity.setBanStatus(1);
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result findByMerchant(Long merchantId) {
        return ResultUtil.success(jpaRepository.findByMerchantId(merchantId));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    @Override
    public void salesAdd(Long id, Integer number) {
        SelfStore one = jpaRepository.findById(id).orElse(null);
        if(one!=null){
            if(one.getSale()!=null){
                one.setSale(one.getSale()+number);
            }else{
                one.setSale(number);
            }
            jpaRepository.save(one);
        }
    }

    @Override
    public Result ban(Long id, Integer banStatus) {
        jpaRepository.banStatus(id, banStatus); //封禁店铺
        goodsJpaRepository.updateStatusByStoreId(banStatus, id); //上下架所有商品
        return ResultUtil.success();
    }

    @Autowired
    private SelfStoreCollectJpaRepository selfStoreCollectJpaRepository;
    @Autowired
    private GoodsJpaRepository goodsJpaRepository;
    @Autowired
    private SelfUserBrowseJpaRepository selfUserBrowseJpaRepository;
    @Autowired
    private OrdersService ordersService;

    @Override
    public Result count(Long storeId,String data) {
        Map<String, Object> map = new HashMap<>();
        //1.收藏店铺数量
        int count1 = selfStoreCollectJpaRepository.findByStoreId(storeId);
        //2.商品总数
        int count2 = goodsJpaRepository.findByStoreId(storeId);
        //3.商品总浏览量
        Integer count3 = goodsJpaRepository.findSumByStoreId(storeId);
        //4.商品今日浏览量
        int count4 = selfUserBrowseJpaRepository.findSumByStoreId(storeId, data);
        //4.本月收入
        Map<String, Object> count5Map = (HashMap) ordersService.income(data, 2, storeId).getData(); //way： 1年 2月 3日
        Object count5 = count5Map.get("sum1");
        //5.今日收入
        Map<String, Object> count6Map = (HashMap) ordersService.income(data, 3, storeId).getData(); //way： 1年 2月 3日
        Object count6 = count6Map.get("sum1");
        map.put("count1", count1); //收藏总数
        map.put("count2", count2); //商品总数
        map.put("count3", count3); //商品总浏览量
        map.put("count4", count4); //商品今日浏览量
        map.put("count5", count5); //本月收入
        map.put("count6", count6); //今日收入
        return ResultUtil.success(map);
    }

    @Override
    public void checkMargin() {
        jpaRepository.checkMargin(DateUtil.createDate());
    }
}
